#include "login.h"

#include "mainwindow.h"

Login::Login( MainWindow* parent, QList<Buceador*>* buceadores )
: QWidget( parent ), _mainwindow( parent )
{
    setObjectName( "loginWidget" );

    _buceadoreslist = new QComboBox();
    _buceadoreslist->setObjectName( "buceadoresCombo" );
    _buceadoreslist->addItem( trUtf8("Selecciona un buceador:") );
    for( int i = 0; i < buceadores->count(); ++i )
    {
        Buceador* b = buceadores->at(i);
        _buceadoreslist->addItem( b->usuario() );
    }
    connect( _buceadoreslist, SIGNAL( currentIndexChanged( int ) ), this, SLOT( buceadorIndexChanged( int ) ) );

    _login = new QPushButton( trUtf8("Entrar") );
    _login->setObjectName( "loginButton" );
    _login->setEnabled( false );
    connect( _login, SIGNAL( clicked() ), this, SLOT( login() ) );

    QVBoxLayout* layout = new QVBoxLayout( this );
    layout->addStretch(1);
    layout->addWidget( _buceadoreslist, 0, Qt::AlignHCenter );
    layout->addWidget( _login, 0, Qt::AlignHCenter );
    layout->addStretch(2);
    setLayout( layout );

    setVisible( false );

    _timeline = new QTimeLine( 1000, this );
    _timeline->setFrameRange( 100, 0 );
    _timeline->setDirection( QTimeLine::Backward );
    connect( _timeline, SIGNAL( frameChanged( int ) ), this, SLOT( update() ) );
    connect( _timeline, SIGNAL( finished() ), this, SLOT( fadedOut() ) );
}

void Login::paintEvent( QPaintEvent* /*event*/ )
{
    QPainter p( this );
    if( _timeline->state() == QTimeLine::Running )
    {
        qreal timevalue = _timeline->currentValue();
        p.setOpacity( timevalue );
    }
    p.fillRect( rect(), "steelblue" );
}

void Login::fadedOut()
{
    hide();
    _buceadoreslist->show();
    _login->show();
}

void Login::keyPressEvent( QKeyEvent* event )
{
    if( ( event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return ) && _buceadoreslist->currentIndex() != 0 ) login();
}

void Login::login()
{
    _mainwindow->showBuceador( _buceadoreslist->currentText() );
    _buceadoreslist->hide();
    _login->hide();
    _timeline->start();
}

void Login::buceadorIndexChanged( int index )
{
    _login->setEnabled( index != 0 );
}
